<?php
/**
 * Created by IntelliJ IDEA.
 * User: admin
 * Date: 3/28 0028
 * Time: 11:47
 */

namespace app\index\controller;


use app\api\model\Jdorder;
use app\index\model\Elelink;
use app\index\model\Eleorder;
use ElemeOpenApi\Api\OrderService;
use ElemeOpenApi\Api\UserService;
use ElemeOpenApi\Config\Config;
use ElemeOpenApi\OAuth\OAuthClient;
use think\Controller;
use think\Session;
use think\View;

class Common extends Controller
{
    /**
     *
     * @return \think\response\View
     */
    public function login(){
        if(request()->isPost()){
            if(model("manager")->checklogin()==false){
                $this->error("账号或密码错误!");
            }else{
                if(Session::get("usertype")==1){
                    return redirect(url("Common/select"));
                }else{
                    $this->success("登录成功",url("Index/index"));
                }
            }
        }else{
            return \view();
        }
    }

    /**
     * 选择门店
     */
    public function select(){
        if(Session::get("usertype")==1||Session::get("merchantid")!=null){
            View::share("res",model("shop")->getonemer(Session::get("merchantid")));
            return \view();
        }else{
            $this->error("您没有权限访问!");
        }
    }

    /**
     * 选择门店操作
     */
    public function selectshop(){
        if(Session::get("usertype")==1||Session::get("merchantid")!=null){
            Session::set("shopid",request()->param("shopid"));
            Session::set("shopname",\model("shop")->getname(request()->param("shopid")));
            return $this->redirect("Index/index");//到首页框架
        }else{
            $this->error("您没有权限访问!");
        }
    }

    /**
     * 空操作
     * @return \think\response\Redirect
     */
    public function _empty(){
        return redirect(url("Common/login"));
    }

    /**
     * 饿了么回调地址
     */
    public function elecallback(){
        if(request()->get("code")){
            $shopid=request()->get("state");
            $config = new Config(\config("elekey"), \config("elesecret"), true);
            //使用config对象，实例化一个授权类
            $client = new OAuthClient($config);
            $token = $client->get_token_by_code(request()->get("code"), "http://fuzzyy.wicp.net/index.php/index/Common/elecallback");
            if(isset($token->access_token)){
                //获取商户账号信息(必须)
                $user_service=new UserService($token,$config);
                $userinfo=$user_service->get_user();
                $arr=[];
                foreach ($userinfo->authorizedShops as $k=>$v){
                    $arr[]=$v->id;
                }
                $ele=new Elelink();
                $ori=$ele->where("shopid",$shopid)->find();
                if($ori){
                    $ele->data([
                        "shopid"=>$shopid,
                        "accesstoken"=>$token->access_token,
                        "expiresin"=>$token->expires_in,
                        "refreshtoken"=>$token->refresh_token,
                        "updatetime"=>time(),
                        "authorizedshops"=>implode(",",$arr),
                        "serializetoken"=>serialize($token)
                    ],["id"=>$ori["id"]]);//更新
                }else{
                    $ele->data([
                        "shopid"=>$shopid,
                        "accesstoken"=>$token->access_token,
                        "expiresin"=>$token->expires_in,
                        "refreshtoken"=>$token->refresh_token,
                        "updatetime"=>time(),
                        "authorizedshops"=>implode(",",$arr),
                        "serializetoken"=>serialize($token)
                    ]);//新增
                }

                $res=$ele->save();

                //调用服务方法，获取资源
                if($res){
                    View::share("res",["status"=>1,"msg"=>"授权成功"]);
                    return \view();
                }else{
                    View::share("res",["status"=>0,"msg"=>"授权失败"]);
                    return \view();
                }
            }else{
                View::share("res",["status"=>0,"msg"=>"授权失败"]);
                return \view();
            }
        }else{
            View::share("res",["status"=>0,"msg"=>"参数错误"]);
            return \view();
        }
    }

    /**
     * 饿了么通知地址
     */
    public function elenotify(){
        $postdata=file_get_contents("php://input");//POST数据
//        return json(["message"=>"ok"]);
        file_put_contents(RUNTIME_PATH."log/ele/".time().".txt","get:".serialize(request()->get()).PHP_EOL."post:".serialize($postdata));//记录日志
        $eleorder=new Eleorder();
        $res=$eleorder->updatedata();
        if($res){
            return json(["message"=>"ok"]);
        }else{
            return json(["message"=>"error"]); //记录不成功
        }
    }

    public function printorder(){
        $config = new Config("EWEuH1WpZK","1ef5873936dd98cf36ff17e3e0c988a6", false);
        $token=new \stdClass();
        $token->access_token="3f707ada7a9b40da51fd2a4094d65460";
        $order_service = new orderService($token, $config);
        $order_id = "1206188377039714415";
        $result = $order_service->get_order($order_id);
        dump($result);
    }


    /**
     * 饿了么绑定用户
     * 可以注释
     */
    public function elegetuser(){
        $config = new Config(\config("elekey"), \config("elesecret"), true);
        //使用config对象，实例化一个授权类
        $token=new \stdClass();
        $token->access_token="b346a7792c709255e2f8c2a531def257";
        $user_service=new UserService($token,$config);
        var_dump($user_service->get_user()->authorizedShops);
    }

    /**
     * 测试跨库查询订单(OK)
     */
    public function  baidutest(){
        $jdmodel=new Jdorder();
        $res=$jdmodel->where("platform",3)->where("orderstarttime",">","2016-11-05")->select();
        echo "<pre>";
        dump($res);
    }

    /**
     * 饿了么定时任务
     * @example 定时举例,每十天执行一次
     * @link crontab 0 0 *\/10 * * curl http://youdomain/index.php/index/common/elecron
     */
    public function elecron(){
        set_time_limit(0);
        ob_start();
        $count=0;
        $config = new Config(\config("elekey"), \config("elesecret"), true);//TODO 正式环境需要更新
        $authclient=new OAuthClient($config);
        //查找已经过期的TOKEN
        $ele=model("elelink");
        $delcount=$ele->where("updatetime+expiresin<".time())->delete();//首先删除那些过期的TOKEN
        $res=$ele->where("updatetime+expiresin>".time())->select();//找到未过期的列表
        foreach ($res as $k=>$v){
            try{
                $newtoken=$authclient->get_token_by_refresh_token($v["refreshtoken"],"all");
                $saveresult=$ele->save([
                    "accesstoken"=>$newtoken->access_token,
                    "expiresin"=>$newtoken->expires_in,
                    "refreshtoken"=>$newtoken->refresh_token,
                    "updatetime"=>time(),
                    "serializetoken"=>serialize($newtoken)
                ],["id"=>$v["id"]]);//更新
                if($saveresult){
                    $count++;
                }
                sleep(1);//休息一秒
            }catch (\Exception $exception){
//                异常时会删除该条授权
                if($ele->where("id",$v["id"])->delete()){
                    echo "删除了".$v["id"]."号记录,";
                }
                echo $exception->getMessage().PHP_EOL;
            }

        }
        echo "成功更新".$count."条,删除了旧记录".$delcount."条";
        file_put_contents(iconv("UTF-8","GBK",RUNTIME_PATH."log/ele/TOKEN日志".time().".txt"),ob_get_contents());//记录日志
        ob_end_flush();
    }

}